define([
  'jquery',
  'views/View',
  'views/media/UploadBoxView',
  'hbs!template/users/upload'
], function($, View, UploadBoxView, template){
  var UploadView = UploadBoxView.extend({
    template: template,

    upload: function(callback) {
      console.log("upload");
      var i, files = this.getFiles();
      for(i=0; i < files.length; i++) {
        var f = files[i].get("file");
        if(f) {
          this.uploadFile(f, callback);
        }
      }
    },

    uploadFile: function(f, callback){
      console.log("UploadFile!!!");
      var that = this;
      var file = f || this.file;

      if(file) {
        // Create a form data
        var fd = new FormData();
        fd.append("data", file);

        // Create the XMLHttpRequest
        var xhr = new XMLHttpRequest();

        // Add events listeners
     /*   xhr.upload.addEventListener("progress", this.uploadProgress, false);
        xhr.addEventListener("load", this.uploadComplete, false);
        xhr.addEventListener("error", this.uploadFailed, false);
        xhr.addEventListener("abort", this.uploadCanceled, false);
*/
        // Send data
        xhr.open("POST", "/api/me/photos", true);
        xhr.onload = function() {
          if(xhr.status === 201) {
            var photo = $.parseJSON(xhr.responseText);
            callback(photo.id, photo.original.source);
          }
        };
        xhr.send(fd);
      }
    }

  });

  return UploadView;
});